<template>
  <div class="chat-container">
    <!-- 聊天消息区域 -->
    <div ref="messageContainer" class="chat-messages">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
        <div :class="['bubble', message.role]">
          {{ message.content }}
        </div>
      </div>
      <!-- 加载指示器 -->
      <div v-if="isLoading" class="message bot">
        <div class="bubble bot">
          <span class="typing-dots"><span></span><span></span><span></span></span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input v-model="userInput" placeholder="请输入您的问题..." @keyup.enter="sendMessage" clearable>
        <template #append>
          <el-button :loading="isLoading" @click="sendMessage" icon="Promotion">发送</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script>
import { startConversation, sendMessage } from "@/api/agroai"; // 导入两个新的API函数

export default {
  data() {
    return {
      messages: [],
      userInput: '',
      isLoading: false,
      conversationId: null, // 在组件data中管理会话ID
    };
  },
  methods: {
    async sendMessage() {
      const message = this.userInput.trim();
      if (!message || this.isLoading) return;

      this.messages.push({ role: 'user', content: message });
      this.userInput = '';
      this.scrollToBottom();

      this.isLoading = true;
      try {
        // 如果没有会话ID，则先创建会话
        if (!this.conversationId) {
          const startResp = await startConversation();
          this.conversationId = startResp.data; // 假设返回数据直接是conversationId字符串
        }
        // 发送用户消息到已有会话
        const response = await sendMessage({
          conversationId: this.conversationId, // 传入后端所需的参数
          message: message
        });
        const aiResponse = response.data; // 根据实际响应结构调整

        this.messages.push({ role: 'bot', content: aiResponse });

      } catch (error) {
        console.error('调用AI接口失败:', error);
        this.$message.error('对话失败: ' + (error.message || '未知错误'));
        this.messages.push({ role: 'bot', content: '抱歉，我好像出了点问题，请再试一次。' });
      } finally {
        this.isLoading = false;
        this.$nextTick(() => { // 使用箭头函数和 $nextTick 确保 this 指向正确且在DOM更新后执行
          this.scrollToBottom();
        });
      }
    },
    scrollToBottom() {
      // 此方法的作用是将消息容器的滚动条滚动到底部
      const container = this.$refs.messageContainer;
      if (container) {
        // 将容器的滚动高度设置为它的滚动高度，即可瞬间滚动到底部
        container.scrollTop = container.scrollHeight;
      }
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 600px;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f5f5;
}

.message {
  display: flex;
  margin-bottom: 16px;
}
.message.user {
  justify-content: flex-end;
}
.message.bot {
  justify-content: flex-start;
}

.bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
  word-break: break-word;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.bubble.user {
  background-color: #1890ff;
  color: white;
  border-bottom-right-radius: 4px;
}
.bubble.bot {
  background-color: white;
  color: #333;
  border: 1px solid #ddd;
  border-bottom-left-radius: 4px;
}

/* 气泡箭头 (可选) [2,4](@ref) */
.bubble.user::after,
.bubble.bot::before {
  content: '';
  position: absolute;
  border: 6px solid transparent;
}
.bubble.user::after {
  right: -12px;
  top: 10px;
  border-left-color: #1890ff;
}
.bubble.bot::before {
  left: -12px;
  top: 10px;
  border-right-color: #ddd;
}
.bubble.bot::after {
  left: -11px;
  top: 10px;
  border-right-color: white;
}

/* 正在输入动画 [6](@ref) */
.typing-dots {
  display: inline-flex;
  align-items: center;
}
.typing-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #999;
  margin: 0 2px;
  animation: typingAnimation 1.4s infinite ease-in-out both;
}
.typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.typing-dots span:nth-child(2) { animation-delay: -0.16s; }
@keyframes typingAnimation {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.input-area {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  background-color: white;
}
</style>
